import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import fs from 'fs'

function generatePagePlugin() {
  return {
    name: 'generate-page',
    buildStart() {
      // 读取所有页面配置
      const generationConfigs = fs.readdirSync(path.resolve(__dirname, 'src/generationConfigs'))
      
      generationConfigs.forEach(configFile => {
        const config = JSON.parse(
          fs.readFileSync(path.resolve(__dirname, `src/generationConfigs/${configFile}`), 'utf-8')
        )
        
        // 生成页面文件
        const pageContent = generatePageTemplate(config)
        const outputPath = path.resolve(__dirname, `src/generated/${configFile.replace('.json', '.vue')}`)
        
        fs.writeFileSync(outputPath, pageContent)
      })
    }
  }
}

function generatePageTemplate(config) {
  const imports = config.components.map(c => 
    `import ${c.component} from '@/viewComponents/${c.component}/index.vue'`
  ).join('\n')

  // 修复组件引用问题
  const componentsDeclaration = config.components.map(c => ({
    ...c,
    component: c.component // 直接使用导入的组件引用
  }))

  return `
<template>
  <${config.layout} :layout-config="layoutConfig"  :components="components" />
</template>

<script setup lang="ts">
${imports}
import ${config.layout} from '@/layouts/${config.layout}/index.vue'

const layoutConfig = ${JSON.stringify(config.layoutConfig, null, 2)}
const components = ${JSON.stringify(componentsDeclaration, null, 2).replace(/"component": "(\w+)"/g, '"component": $1')}
</script>
`
}

// 重构后的proxy配置，支持从env中读取JSON格式的多代理配置
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  
  // 解析代理配置
  let proxyConfig = {}
  if (env.VITE_PROXY) {
    try {
      proxyConfig = JSON.parse(env.VITE_PROXY)
    } catch (e) {
      console.error('Error parsing VITE_PROXY:', e)
    }
  }

  return {
    base: env.VITE_BASE_URL,
    server: {
      proxy: proxyConfig
    },
    plugins: [vue(), generatePagePlugin()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
  }
})
